extends Node
class_name Enemy

# 基本信息
@export var enemy_name: String = "未知敌人"
@export var level: int = 1
@export var experience_reward: int = 10  # 击败后获得的经验值

# 敌人类型
enum EnemyType {
	BEAST,      # 妖兽
	CULTIVATOR, # 修士
	SPIRIT,     # 灵体
	DEMON,      # 魔物
	BOSS        # 首领
}

@export var enemy_type: int = EnemyType.BEAST

# 基础属性
@export var max_health: int = 50
@export var current_health: int = 50
@export var max_spirit: int = 20  # 真气值
@export var current_spirit: int = 20
@export var attack: int = 8
@export var defense: int = 3
@export var speed: int = 8

# 掉落物品
var drop_table: Array = []  # 包含物品和掉落几率的字典数组
var spirit_stone_drop: Dictionary = {"min": 0, "max": 10}  # 掉落灵石范围

# 技能列表
var skills: Array = []  # 敌人可用技能

# AI行为模式
enum AIBehavior {
	AGGRESSIVE,  # 主动攻击
	DEFENSIVE,   # 防御为主
	SUPPORT,     # 辅助型
	RANDOM,      # 随机行动
	STRATEGIC,   # 策略型
}

@export var ai_behavior: int = AIBehavior.AGGRESSIVE

# 信号
signal health_changed(current, maximum)
signal died()

# 初始化敌人
func _init(p_name: String = "未知敌人", p_level: int = 1) -> void:
	name = p_name
	level = p_level
	
	# 根据等级调整属性
	_scale_stats_by_level()

# 根据等级调整属性
func _scale_stats_by_level() -> void:
	max_health = int(50 * (1 + 0.2 * level))
	max_spirit = int(20 * (1 + 0.15 * level))
	attack = int(8 * (1 + 0.1 * level))
	defense = int(3 * (1 + 0.1 * level))
	speed = int(8 * (1 + 0.05 * level))
	
	current_health = max_health
	current_spirit = max_spirit
	
	# 调整经验奖励
	experience_reward = 10 * level

# 计算攻击伤害（带随机性）
func calculate_damage(base_damage: int) -> int:
	# 添加随机波动，范围为基础伤害的±20%
	var variation_percent = randf_range(-0.2, 0.2)
	var damage_variation = int(base_damage * variation_percent)
	
	# 根据敌人类型可以调整随机性
	if enemy_type == EnemyType.BOSS:
		# Boss的攻击更加稳定，波动更小
		damage_variation = int(damage_variation * 0.5)
	elif enemy_type == EnemyType.BEAST:
		# 妖兽攻击更加狂野，波动更大
		damage_variation = int(damage_variation * 1.5)
	
	# 计算最终伤害，确保至少为1
	var final_damage = max(1, base_damage + damage_variation)
	return final_damage

# 受到伤害
func take_damage(amount: int) -> void:
	# 应用防御力减免并确保最小伤害为1
	current_health -= max(1, amount - defense / 2)
	current_health = max(0, current_health)
	
	emit_signal("health_changed", current_health, max_health)
	
	if current_health <= 0:
		emit_signal("died")

# 治疗生命值
func heal(amount: int) -> void:
	current_health += amount
	current_health = min(current_health, max_health)
	
	emit_signal("health_changed", current_health, max_health)

# 消耗真气
func consume_spirit(amount: int) -> bool:
	if current_spirit >= amount:
		current_spirit -= amount
		return true
	return false

# 恢复真气
func recover_spirit(amount: int) -> void:
	current_spirit += amount
	current_spirit = min(current_spirit, max_spirit)

# 添加技能
func add_skill(skill) -> void:
	skills.append(skill)

# 添加掉落物品
func add_drop(item, chance: float) -> void:
	drop_table.append({"item": item, "chance": chance})

# 设置灵石掉落范围
func set_spirit_stone_drop(min_amount: int, max_amount: int) -> void:
	spirit_stone_drop = {"min": min_amount, "max": max_amount}

# 生成掉落物品
func generate_drops() -> Dictionary:
	var drops = {
		"items": [],
		"spirit_stones": 0
	}
	
	# 计算物品掉落
	for drop in drop_table:
		if randf() <= drop.chance:
			drops.items.append(drop.item)
	
	# 计算灵石掉落
	if spirit_stone_drop.max > 0:
		drops.spirit_stones = randi_range(spirit_stone_drop.min, spirit_stone_drop.max)
	
	return drops

# AI决策 - 在战斗中选择行动
func choose_action(player, available_actions: Array) -> Dictionary:
	# 默认行动
	# 计算带随机性的攻击伤害
	var base_damage = calculate_damage(attack)
	var action = {"type": "attack", "target": player, "damage": base_damage}
	
	# 根据AI行为模式选择不同策略
	match ai_behavior:
		AIBehavior.AGGRESSIVE:
			# 优先使用攻击技能
			if skills.size() > 0 and current_spirit >= 10 and randf() < 0.7:
				var attack_skills = []
				
				# 筛选攻击技能
				for skill in skills:
					if skill.skill_type == 0 and skill.current_cooldown == 0 and current_spirit >= skill.spirit_cost:
						attack_skills.append(skill)
				
				if attack_skills.size() > 0:
					var selected_skill = attack_skills[randi() % attack_skills.size()]
					action = {"type": "skill", "skill": selected_skill, "target": player}
					
		AIBehavior.DEFENSIVE:
			# 在生命值低时优先使用治疗技能
			if current_health < max_health * 0.5 and current_spirit >= 10:
				var heal_skills = []
				
				# 筛选治疗技能
				for skill in skills:
					if skill.skill_type == 1 and skill.current_cooldown == 0 and current_spirit >= skill.spirit_cost:
						heal_skills.append(skill)
				
				if heal_skills.size() > 0:
					var selected_skill = heal_skills[randi() % heal_skills.size()]
					action = {"type": "skill", "skill": selected_skill, "target": self}
					
		AIBehavior.SUPPORT:
			# 优先使用增益/减益技能
			if skills.size() > 0 and current_spirit >= 10 and randf() < 0.8:
				var buff_skills = []
				
				# 筛选增益/减益技能
				for skill in skills:
					if (skill.skill_type == 2 or skill.skill_type == 3) and skill.current_cooldown == 0 and current_spirit >= skill.spirit_cost:
						buff_skills.append(skill)
				
				if buff_skills.size() > 0:
					var selected_skill = buff_skills[randi() % buff_skills.size()]
					
					# 增益技能用于自己，减益技能用于玩家
					var target = self if selected_skill.skill_type == 2 else player
					action = {"type": "skill", "skill": selected_skill, "target": target}
					
		AIBehavior.RANDOM:
			# 随机选择行动
			var rand = randf()
			
			if rand < 0.6 or skills.size() == 0:
				# 60%几率普通攻击
				action = {"type": "attack", "target": player, "damage": base_damage}
			else:
				# 40%几率使用随机技能
				var usable_skills = []
				
				for skill in skills:
					if skill.current_cooldown == 0 and current_spirit >= skill.spirit_cost:
						usable_skills.append(skill)
				
				if usable_skills.size() > 0:
					var selected_skill = usable_skills[randi() % usable_skills.size()]
					
					# 根据技能类型选择目标
					var target = player
					if selected_skill.skill_type == 1 or selected_skill.skill_type == 2:  # 治疗或增益
						target = self
					
					action = {"type": "skill", "skill": selected_skill, "target": target}
					
		AIBehavior.STRATEGIC:
			# 策略型AI，根据战斗情况做出最优决策
			
			# 生命值低时优先治疗
			if current_health < max_health * 0.3:
				var heal_skills = []
				
				for skill in skills:
					if skill.skill_type == 1 and skill.current_cooldown == 0 and current_spirit >= skill.spirit_cost:
						heal_skills.append(skill)
				
				if heal_skills.size() > 0:
					var selected_skill = heal_skills[randi() % heal_skills.size()]
					action = {"type": "skill", "skill": selected_skill, "target": self}
					return action
			
			# 玩家生命值低时使用强力攻击技能
			if player.current_health < player.max_health * 0.5:
				var attack_skills = []
				
				for skill in skills:
					if skill.skill_type == 0 and skill.current_cooldown == 0 and current_spirit >= skill.spirit_cost:
						attack_skills.append(skill)
				
				if attack_skills.size() > 0:
					# 选择伤害最高的技能
					var best_skill = attack_skills[0]
					for skill in attack_skills:
						if skill.base_power > best_skill.base_power:
							best_skill = skill
					
					action = {"type": "skill", "skill": best_skill, "target": player}
					return action
			
			# 如果没有特殊情况，使用普通攻击
			action = {"type": "attack", "target": player, "damage": base_damage}

	return action
